package com.example.lib_base.base

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.SPUtils
import com.example.lib_base.view.Res
import com.example.lib_base.view.Res2
import kotlinx.coroutines.launch

open class BaseViewModel:ViewModel() {
    val onFailed by lazy {
        MutableLiveData<Throwable>()
    }
    fun executeNetwork(
        s:suspend ()-> Res,
        success:(String)->Unit,
        failed:(Throwable)->Unit=onFailed::postValue,
        okCode:Int=200
    ){
        viewModelScope.launch {
            try {
                val res=s.invoke()
                SPUtils.getInstance().put("token",res.home)
                Log.i("TagA","res:${res}")
                if (res.statuesCode.toInt()==okCode){
                    success(res.values)
                }else{
                    failed(RuntimeException(res.msg))
                }
            }catch (e:Exception){
                failed(e)
            }
        }
    }
    fun <T> executeNetWorkT(
        s: suspend () -> Res2<T>,
        success: (T) -> Unit,
        failed: (Throwable) -> Unit=onFailed::postValue,
        okCode:Int=200
    ){
        viewModelScope.launch {
            try {
                val res2=s.invoke()
                if (res2.code==okCode){
                    success(res2.data)
                }else{
                    failed(RuntimeException(res2.message))
                }
            }catch (e:Exception){
                failed(e)
            }
        }
    }
}